<?php

/**
* This controller sends email with gmail.
 * The plan is to have his controller to handle all the email-sendings,
 * whatever it is about accountconfirmation og resetting password.
*/

class email extends CI_Controller
{
    function __construct()
    {
            parent::__construct();
            session_start();
    }

    // generates the index page to send an email with a auto generated password
    function index()
    {
        $this->load->model('model_email');
        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => 465,
            'smtp_user' => 'fullyjacked@gmail.com',
            'smtp_pass' => 'fullyjacked1234',
            'mailtype'  => 'html',
            'charset'   => 'iso-8859-1'
         );
        
        
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $id = $this->model_email->emailValidation();
        error_log($id);
        // checks if email is valid if not it will redirect to reset_passwordview
        if ($this->form_validation->run() == FALSE)
        {
            $data['main_content'] = 'publicviews/reset_passwordview';
            $this->load->view('includes/template', $data);
        }
        // If email is valid and an userid is returned
        else if ($id > 0)
        {
            $email = $this->input->post('email');
            $this->load->library('email', $config);
            $this->email->set_newline("\r\n");

            // generates an email with a new autogenerated password and sends it
            $newpass = $this->model_email->newPasswordStr();
            $this->email->from('fullyjacked@gmail.com', 'Fully Jacked');
            $this->email->to($email);
            $this->email->Subject('Welcome to Fully Jacked, Big Guy or Big girl!');
            $this->email->message('Your new password is: ' . $newpass . '/n We recomend that you make a new password!');

            // if email is send succesfully load email_confirm view and
            // update password in the db.
            if($this->email->send())
            {
                error_log($newpass);
                $data['main_content'] = 'emailviews/email_confirm';
                $this->load->view('includes/template', $data);
                $this->model_email->updatePassword($id, $newpass);
            }

            // else report error
            else
            {
                $data['main_content'] = 'publicviews/reset_passwordview';
                $this->load->view('includes/template', $data);

                echo show_error($this->email->print_debugger());
            }
        }
    }
}

